<?php
require_once('../../core.inc.php');
require_once('Model/SiteManage.php');
require_once('View/Smarty.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
require_once('Model/Uploader.php');
require_once('Plugin/Category.php');

$sys = new Model_SiteManage();
$sys->checkLogin();
$params    = $_REQUEST;
$smarty    = new View_Smarty($params);
$category  = new Model_Category();

if (isset($params['do']) && function_exists('exec_' . $params['do'])){
   $params['op'] = call_user_func('exec_' . $params['do'], &$params, &$smarty, &$category);
}
if (isset($params['op']) && function_exists('op_' . $params['op'])){
    call_user_func('op_' . $params['op'], $params, &$smarty, &$category);
}
else{
    call_user_func('op_search', $params, &$smarty, &$category);
}
//
//一覧表示
function op_search($params, &$smarty, &$category)
{
    $list  = $category->getList(array(), $orderby = 'level, order_num');
    $child = array();
    foreach($list as $row){
        $child[$row['parent']][$row['id']] = $row;
    }
    $smarty->assign('child', $child);
    $smarty->display('category/category_index.html');
}
// 編集
function op_edit($params, &$smarty, &$category)
{
    if (!isset($params['id']) || !isset($params['level'])){
        __raise_error();
    }
    $db    = new Model_DB();
    $id    = $params['id'];
    $level = $params['level'];
    if (!isset($params['forms'])){
        global $sys;
        $forms = array();
        if( $id == '1' ){
            $forms['category_name'] = 'ルートカテゴリ';
        }else{
            $c = $category->get($id);
            $forms['category_name'] = $c['category_name'];
            if ($c['filename'] != ''){
                $forms['filename']    = array();
                $forms['filename'][0] = $sys->getCurrentSiteUrl() . 'images/' . $c['filename'];
            }
            else{
                $forms['filename'] = array();
            }
        }
        $list       = $category->getList(array("parent" => $id, "site" => $sys->getCurrentSite()));
        $form_child = array();
        foreach($list as $row){
            $forms_child['child_category'][] = $row['category_name'];
            $forms_child['status'][]         = $row['status'];
            $forms_child['array_id'][]       = $row['id'];
        }
        if( !isset( $forms_child['child_category'] ) || count( $forms_child['child_category'] ) == 0 ){
            $forms_child['child_category'][0] = '';
            $forms_child['status'][0]         = '1';
            $forms_child['array_id'][0]       = '';
        }
        $params['forms']       = $forms;
        $params['forms_child'] = $forms_child;
    }
    $smarty->assign('id', $id);
    $smarty->assign('level', $level);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params["forms"]);
    $smarty->assign('forms_child', $params["forms_child"]);
    $smarty->display('category/category_form.html');
}
function exec_validate_update_form(&$params, &$smarty, &$category)
{
    if (!isset($params['id']) || !isset($params['level'])){
        __raise_error();
    }
    if ($params['mode'] == 'delete')
    {
        return exec_delete_form($params, $smarty, $category);
    }
    $err = array();
    if($category->validate($params['forms'], $err)){
        return exec_update_form($params, $smarty, $category);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'edit';
}
function exec_update_form(&$params, &$smarty, &$category)
{
    if(isset($params['forms']['filename'])){
        $tmp_filename = $params['forms']['filename'];
        unset($params['forms']['filename']);
    }
    $db    = new Model_DB();
    $id    = $params['id'];
    $level = $params['level'];
    if($id > 1){
        $category->update($id, $params['forms']);
    }
    //画像
/*
    if(isset($tmp_filename)){
        $uploader  = new Model_Uploader();
        $cache     = $tmp_filename[0];
        $base_name = 'image_'.$id;
        $move_to   = $category->getSiteDir($mkdir = 1);
        if (!file_exists($move_to. 'images/')){
            mkdir($move_to.'images/');
            chmod($move_to.'images/', 0777);
        }
        $move_to .= 'images/';
        $filename = $uploader->moveCacheImage($cache, $move_to, $base_name);
        $data = array();
        $data['filename'] = $filename;
        $category->update($id, $data);
    }
*/
    //子カテゴリ
    global $sys;
    foreach( $params['forms_child']['child_category'] as $k => $v ){
        $v = trim( $v );
        if (isset($params['forms_child']['array_id'][$k]) && $params['forms_child']['array_id'][$k] != ''){
            if( $v != '' ){
                // 更新
                $sql = sprintf("UPDATE M_CATEGORY SET site_id = %u, category_name = '%s', status = '%s', parent = %u, level = %u, order_num = %u WHERE id = %u",
                        $sys->getCurrentSite(),
                        $db->escape( $v ),
                        $params['forms_child']['status'][$k],
                        $id,
                        ($level + 1),
                        $order_num,
                        $params['forms_child']['array_id'][$k] );
            }else{
                // 削除
                $sql = sprintf("DELETE FROM M_CATEGORY WHERE id = %u", $params['forms_child']['array_id'][$k] );
            }
            $db->query( $sql );
        }
        else
        {
            // 新規登録
            if( $v != '' ){
                $sql = sprintf( "INSERT INTO M_CATEGORY(id, site_id, category_name,status,parent,level,order_num) VALUES( %u, %u, '%s', '%s', %u, %u, %u )",
                        $category->get_ID(),
                        $sys->getCurrentSite(),
                        $db->escape( $v ),
                        $params['forms_child']['status'][$k],
                        $id,
                        ($level + 1),
                        $order_num
                );
                $db->query( $sql );
            }
        }
        $order_num++;
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=edit_complete&id='.$id.'&level='.$params['level']);
    exit();
}
function op_edit_complete($params, &$smarty, &$staff)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('forms', array('id' => $params['id'], 'level' => $params['level']));
    }
    $smarty->assign('message', '更新が完了しました');
    $smarty->display('category/category_form.html');
}
//　削除
function exec_delete_form(&$params, &$smarty, &$category)
{
    if (!isset($params['id'])){
        __raise_error();
    }

    $res = $category->delete($params['id']);
    if($res){
        //子カテゴリも削除
        $list = $category->getList(array("parent"=>$params['id']));
        foreach($list as $id => $one)
        {
            $category->delete($id);
        }
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=delete_complete&id=' . $id);
    exit();
}
function op_delete_complete($params, &$smarty, &$news)
{
    $smarty->assign('phase', 'complete');
    $smarty->assign('message', '削除が完了しました');
    $smarty->display('category/category_form.html');
}
// カテゴリ選択
function op_select_category(&$params, &$smarty, &$category)
{
    $list  = $category->getList(array(), $orderby = 'level, order_num');
    $child = array();
    foreach($list as $row){
        $child[$row['parent']][$row['id']] = $row;
    }
    $smarty->assign('child', $child);
    $smarty->assign('parent', $params["parent"] );
    $smarty->display('category/select_category.html');
}
function op_get_category_list(&$params, &$smarty, &$category)
{
    $list = array();
    foreach($category->getList(array(), $orderby = 'level, order_num') as $row){
        $list[$row['id']] = $row;
    }
    echo(json_encode($list));
    exit();
}

?>